package com.deveye.weatherApi;


import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by Administrator on 2017/7/12.
 */
public class WeatherApi {
    //西安天气
    private static String url = "https://api.heweather.com/x3/weather?cityid=CN101050311&key=486806198bb24ce19a26ef9643b5013f";

    public static String getWeather() throws Exception{
        HttpClient httpClient = new HttpClient();
        GetMethod getMethod = new GetMethod(url);
        getMethod.setRequestHeader("Content-Type","application/json");
        httpClient.executeMethod(getMethod);
        InputStream inputStream = getMethod.getResponseBodyAsStream();
        byte[] datas = null;
        datas =  readInputStream(inputStream);
        String result = new String(datas,"UTF-8");
        System.out.print(result);
        return result;
    }

    private static byte[] readInputStream(InputStream inputStream) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1){
            outputStream.write(buffer,0,len);
        }
        byte[] data = outputStream.toByteArray();
        outputStream.close();
        inputStream.close();
        return data;

    }

    public static void  downLoadFromUrl(String urlStr,String fileName,String savePath) throws IOException{
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        //设置超时间为3秒
        conn.setConnectTimeout(3*1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        //得到输入流
        InputStream inputStream = conn.getInputStream();
        //获取自己数组
        byte[] getData = readInputStream(inputStream);

        //文件保存位置
        File saveDir = new File(savePath);
        if(!saveDir.exists()){
            saveDir.mkdir();
        }
        File file = new File(saveDir+File.separator+fileName);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(getData);
        if(fos!=null){
            fos.close();
        }
        if(inputStream!=null){
            inputStream.close();
        }


        System.out.println("info:"+url+" download success");

    }

    public static void main(String[] args) {
        try{
            downLoadFromUrl("http://mmbiz.qpic.cn/mmbiz_jpg/B3JxeicINToRVfSAlOq9llbic9EAcdibWfILBP9LVnibQuWTy09EWiaNtckDoacdRkYWCzjFwID4U7DYOXupVBFrWAA/0",
                    "百度.jpg","d:/images/");
        }catch (Exception e) {
            // TODO: handle exception
        }
    }
}
